package com.rentong.wx.cust.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.util.StringUtil;
import com.rentong.page.Page;
import com.rentong.wx.cust.dao.*;
import com.rentong.wx.cust.domain.*;
import com.rentong.wx.cust.dto.*;

import com.rentong.wx.cust.service.CustCanyinquanService;
import com.rentong.wx.sys.dao.SysCityDao;
import com.rentong.wx.sys.dao.SysConfCanyinquanShenheDao;
import com.rentong.wx.sys.dao.SysConfChongzhiBstDao;
import com.rentong.wx.sys.domain.SysCityEntity;
import com.rentong.wx.sys.domain.SysConfCanyinquanShenheEntity;
import com.rentong.wx.sys.domain.SysConfChongzhiBstEntity;
import com.rentong.wx.utils.IpAddressUtil;
import com.rentong.wx.utils.TencentMapReverseGeocoding;
import com.rentong.wx.utils.TimeFormatter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CustCanyinquanServiceImpl implements CustCanyinquanService {

    @Resource
    private CustCanyinquanDao custCanyinquanDao;

    @Autowired
    private SysCityDao sysCityDao;

    @Autowired
    private SysConfCanyinquanShenheDao sysConfCanyinquanShenheDao;

    @Autowired
    private SysConfChongzhiBstDao sysConfChongzhiBstDao;

    @Autowired
    private CustCanyinquanPicDao custCanyinquanPicDao;

    @Autowired
    private CustCanyinquanDianzanDao custCanyinquanDianzanDao;

    @Autowired
    private CustCanyinquanPinglunDao custCanyinquanPinglunDao;

    @Autowired
    private WxCustUserMapper wxCustUserMapper;

    @Autowired
    private CustCanyinquanDianzanArticleDao custCanyinquanDianzanArticleDao;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<CustCanyinquanDto> getCanyinquanList(CustCanyinquanEntityDto custCanyinquanEntityDto) {
        List<CustCanyinquanDto> list = custCanyinquanDao.getCanyinquanList(custCanyinquanEntityDto);

        for (int i = 0; i < list.size(); i++) {
            List<CustCanyinquanPicEntity> ccList = custCanyinquanPicDao.getPicByCanyinquanId(list.get(i).getCanyinquanId());
            list.get(i).setListCanyinquanPic(ccList);
        }

        return list;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Page getCustCanyinquanList(Long cityId, String content, BigDecimal longitude, BigDecimal latitude, Integer sort, Long canyinquanLabelId, Integer pageNum, Integer pageSize, Long custId) {
        List<CustCanyinquanDto> custCanyinquanList = custCanyinquanDao.getCustCanyinquanList(cityId, content, longitude, latitude, sort, canyinquanLabelId, pageNum, pageSize);

        //把图片加进去
        for (int i = 0; i < custCanyinquanList.size(); i++) {
            custCanyinquanList.get(i).setListCanyinquanPic(custCanyinquanPicDao.getPicByCanyinquanId(custCanyinquanList.get(i).getCanyinquanId()));

            //是否己点赞
            CustCanyinquanDianzanArticleEntity article = new CustCanyinquanDianzanArticleEntity();
            article.setCustId(custId);
            article.setCanyinquanId(custCanyinquanList.get(i).getCanyinquanId());
            CustCanyinquanDianzanArticleEntity article1 = custCanyinquanDianzanArticleDao.selectOne(article);
            if (ObjectUtil.isNotEmpty(article1)) {
                custCanyinquanList.get(i).setIsDianzan(1);
            } else {
                custCanyinquanList.get(i).setIsDianzan(2);
            }

        }

        Integer count = wxCustUserMapper.getCustUserTotalNum();
        Page page = new Page();
        page.setTotalNum(count);
        page.setResultList(custCanyinquanList);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CustCanyinquanDto getDynamicName(Long custId, Long canyinquanId) {
        Integer flag = 0;

        CustCanyinquanDto dynamicName = custCanyinquanDao.getDynamicName(canyinquanId);

        List<CustGuanzhuEntity> guanZhu = custCanyinquanDao.getGuanZhu(dynamicName.getCustId(), custId);

        if (guanZhu != null && guanZhu.size() == 2) {
            //互相关注
            flag = 2;
        } else if (guanZhu != null && guanZhu.size() == 0) {
            //未关注
            flag = 0;
        } else if (guanZhu != null && guanZhu.size() == 1) {

            if (guanZhu.get(0).getCustId().toString().equals(custId.toString())) {
                //已经点关注
                flag = 1;
            } else {
                //未关注
                flag = 0;
            }

        } else {
            //未关注
            flag = 0;
        }

        dynamicName.setFlag(flag);
        dynamicName.setFormatDate(TimeFormatter.formatDate(dynamicName.getAddTime()));

        //添加详情中的轮播图
        dynamicName.setListCanyinquanPic(custCanyinquanPicDao.getPicByCanyinquanId(canyinquanId));

        return dynamicName;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Page getPingLun(Long canyinquanId, Long custId, Integer pageNum, Integer pageSize) {
        List<CommentDto> pingLun = custCanyinquanDao.getPingLun(canyinquanId, custId, pageNum, pageSize);

        for (int i = 0; i < pingLun.size(); i++) {
            pingLun.get(i).setFormatDate(TimeFormatter.formatDate(pingLun.get(i).getAddTime()));

            //查出每个大评论下面的子评论
            List<CommentDto> childPingLun = custCanyinquanDao.getChildPingLun(pingLun.get(i).getCanyinquanPinglunId(), custId, pageNum, pageSize);
            for (int j = 0; j < childPingLun.size(); j++) {
                childPingLun.get(j).setFormatDate(TimeFormatter.formatDate(childPingLun.get(j).getAddTime()));
            }
            pingLun.get(i).setChild(childPingLun);
        }

        //计算评论的总数
        Integer totalNum = custCanyinquanDao.getTotalNum(canyinquanId);

        Page page = new Page();
        page.setResultList(pingLun);
        page.setTotalNum(totalNum);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<CommentDto> getLoadChildPingLun(Long canyinquanPinglunId, Long custId, Integer pageNum, Integer pageSize) {

        //查出每个大评论下面的子评论
        List<CommentDto> childPingLun = custCanyinquanDao.getChildPingLun(canyinquanPinglunId, custId, pageNum, pageSize);
        for (int j = 0; j < childPingLun.size(); j++) {
            childPingLun.get(j).setFormatDate(TimeFormatter.formatDate(childPingLun.get(j).getAddTime()));
        }

        return childPingLun;
    }


//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void insertPinglun1(Long fuId,Long custId,String pinglunContent,Long canyinquanId) {
//        CustCanyinquanPinglunEntity custCanyinquanPinglunEntity = new CustCanyinquanPinglunEntity();
//        if(fuId==0){
//            custCanyinquanPinglunEntity.setPinglunLevel(1);
//        }
//        else{
//            CustCanyinquanPinglunEntity custCanyinquanPinglunFu = custCanyinquanPinglunDao.selectByPrimaryKey(fuId);
//            if(custCanyinquanPinglunFu.getPinglunLevel()==1)
//                custCanyinquanPinglunEntity.setPinglunLevel(2);
//            else
//                custCanyinquanPinglunEntity.setPinglunLevel(3);
//            custCanyinquanPinglunEntity.setPinglunLevelCustId(custCanyinquanPinglunFu.getCustId());
//        }
//        custCanyinquanPinglunEntity.setCustId(custId);
//        custCanyinquanPinglunEntity.setFuId(fuId);
//        custCanyinquanPinglunEntity.setCanyinquanId(canyinquanId);
//        custCanyinquanPinglunEntity.setPinglunContent(pinglunContent);
//        custCanyinquanPinglunEntity.setIpAddress(wxCustUserMapper.getUserByCustId(custId).getCityName());
//        custCanyinquanPinglunEntity.setAddTime(new Date());
//
//        custCanyinquanPinglunDao.insertSelective(custCanyinquanPinglunEntity);
//
//        //增加评论的数量
//        CustCanyinquanEntity custCanyinquanEntity = custCanyinquanDao.selectByPrimaryKey(canyinquanId);
//        CustCanyinquanEntity cc = new CustCanyinquanEntity();
//        cc.setCanyinquanId(custCanyinquanEntity.getCanyinquanId());
//        cc.setPinglunNum(custCanyinquanEntity.getPinglunNum() + 1);
//        cc.setUpdateTime(new Date());
//        custCanyinquanDao.updateByPrimaryKeySelective(cc);
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertPinglun(CustCanyinquanPinglunEntity custCanyinquanPinglunEntity) {
        custCanyinquanPinglunEntity.setIpAddress(IpAddressUtil.getIpAddressByOnline(custCanyinquanPinglunEntity.getIpAddress()));
        custCanyinquanPinglunEntity.setAddTime(new Date());

        custCanyinquanPinglunDao.insertSelective(custCanyinquanPinglunEntity);

        //增加评论的数量
        CustCanyinquanEntity custCanyinquanEntity = custCanyinquanDao.selectByPrimaryKey(custCanyinquanPinglunEntity.getCanyinquanId());
        CustCanyinquanEntity cc = new CustCanyinquanEntity();
        cc.setCanyinquanId(custCanyinquanEntity.getCanyinquanId());
        cc.setPinglunNum(custCanyinquanEntity.getPinglunNum() + 1);
        cc.setUpdateTime(new Date());
        custCanyinquanDao.updateByPrimaryKeySelective(cc);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrDelDianzan(Long canyinquanPinglunId, Integer type, Long custId) {
        if (type == 1) {
            //判断是否重复点赞
            CustCanyinquanDianzanEntity custCanyinquanDianzanEntity = new CustCanyinquanDianzanEntity();
            custCanyinquanDianzanEntity.setCanyinquanPinglunId(canyinquanPinglunId);
            custCanyinquanDianzanEntity.setCustId(custId);
            List<CustCanyinquanDianzanEntity> select = custCanyinquanDianzanDao.select(custCanyinquanDianzanEntity);
            if (CollectionUtil.isNotEmpty(select)) {
                return;
            }

            //点赞
            CustCanyinquanDianzanEntity ccd = new CustCanyinquanDianzanEntity();
            ccd.setCanyinquanPinglunId(canyinquanPinglunId);
            ccd.setCustId(custId);
            ccd.setAddTime(new Date());
            custCanyinquanDianzanDao.insertSelective(ccd);

            //文章表，修改数据
            CustCanyinquanPinglunEntity ccp = custCanyinquanPinglunDao.selectByPrimaryKey(canyinquanPinglunId);


            //评论表，修改数据
            CustCanyinquanPinglunEntity custCanyinquanPinglunEntity = new CustCanyinquanPinglunEntity();
            custCanyinquanPinglunEntity.setCanyinquanPinglunId(ccp.getCanyinquanPinglunId());
            custCanyinquanPinglunEntity.setPinglunDianzan(ccp.getPinglunDianzan() + 1);
            custCanyinquanPinglunEntity.setUpdateTime(new Date());
            custCanyinquanPinglunDao.updateByPrimaryKeySelective(custCanyinquanPinglunEntity);

        } else {
            //取消点赞
            custCanyinquanDianzanDao.delDianzan(canyinquanPinglunId, custId);


            CustCanyinquanPinglunEntity ccp = custCanyinquanPinglunDao.selectByPrimaryKey(canyinquanPinglunId);

            //评论表，修改数据
            CustCanyinquanPinglunEntity custCanyinquanPinglunEntity = new CustCanyinquanPinglunEntity();
            custCanyinquanPinglunEntity.setCanyinquanPinglunId(ccp.getCanyinquanPinglunId());
            custCanyinquanPinglunEntity.setPinglunDianzan(ccp.getPinglunDianzan() - 1);
            custCanyinquanPinglunEntity.setUpdateTime(new Date());
            custCanyinquanPinglunDao.updateByPrimaryKeySelective(custCanyinquanPinglunEntity);
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCanyinquanState(Long canyinquanId, Integer type, Long custId) {
        CustCanyinquanEntity cc = new CustCanyinquanEntity();
        cc.setCanyinquanId(canyinquanId);

        if (type == 1) {
            //1：下架
            cc.setCanyinquanState(4);
        } else if (type == 2) {
            //2：拨打电话
            CustCanyinquanEntity custCanyinquanEntity = custCanyinquanDao.selectByPrimaryKey(canyinquanId);
            cc.setPhoneNum(custCanyinquanEntity.getPhoneNum() + 1);
        } else if (type == 3) {
            //3：转发
            CustCanyinquanEntity custCanyinquanEntity = custCanyinquanDao.selectByPrimaryKey(canyinquanId);
            cc.setZhuanfaNum(custCanyinquanEntity.getZhuanfaNum() + 1);
        } else if (type == 4) {
            //4：删除
            cc.setCanyinquanState(5);
        }

        custCanyinquanDao.updateByPrimaryKeySelective(cc);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveCanyinquan(SaveCanyinquanDto saveCanyinquanDto, Long custId) {
        boolean result = check(saveCanyinquanDto);
        if (result) {
            //插入cust_canyinquan
            CustCanyinquanEntity custCanyinquanEntity = new CustCanyinquanEntity();
            BeanUtils.copyProperties(saveCanyinquanDto, custCanyinquanEntity);
            custCanyinquanEntity.setCustId(custId);
            //获取城市id
            String cityName = TencentMapReverseGeocoding.getCity(saveCanyinquanDto.getLongitude().toString(), saveCanyinquanDto.getLatitude().toString());
            SysCityEntity cityEntity = sysCityDao.getCityByName(cityName);
            custCanyinquanEntity.setCityId(cityEntity.getCityId());
            custCanyinquanEntity.setCityName(cityName);
            //系统中发布餐饮圈是否需要审核
            SysConfCanyinquanShenheEntity canyinquanShenheEntity = sysConfCanyinquanShenheDao.getCanyinquanShenheEntity();
            custCanyinquanEntity.setCanyinquanState(canyinquanShenheEntity.getShenheState() == 1 ? 2 : 1);

            if (ObjectUtil.isNotEmpty(saveCanyinquanDto.getBstId())) {
                SysConfChongzhiBstEntity chongzhiBst = sysConfChongzhiBstDao.getByBstidAndType(saveCanyinquanDto.getBstId());
                String bstTitle = chongzhiBst.getBstTitle();
                int indexOfDay = bstTitle.indexOf("天");
                int days = Integer.parseInt(bstTitle.substring(0, indexOfDay).trim());
                Date date = DateUtil.date();
                DateTime newDate = DateUtil.offsetDay(date, days);
                custCanyinquanEntity.setToutiaoUtilTime(newDate);
            }
            custCanyinquanEntity.setUpdateTime(new Date());
            custCanyinquanEntity.setAddTime(new Date());
            custCanyinquanDao.save(custCanyinquanEntity);

            //插入cust_canyinquan_pic
            List<CustCanyinquanPicEntity> canyinquanPicEntities = new ArrayList<>();
            List<String> picList = saveCanyinquanDto.getNonEmptyPictures();
            for (String canyinquanPic : picList) {
                CustCanyinquanPicEntity custCanyinquanPicEntity = new CustCanyinquanPicEntity();
                custCanyinquanPicEntity.setCanyinquanId(custCanyinquanEntity.getCanyinquanId());
                custCanyinquanPicEntity.setCanyinquanPicUrl(canyinquanPic);
                custCanyinquanPicEntity.setAddTime(new Date());
                canyinquanPicEntities.add(custCanyinquanPicEntity);
            }
            custCanyinquanPicDao.savaBatch(canyinquanPicEntities);
            return custCanyinquanEntity.getCanyinquanId();
        }
        return -1L;
    }

    public boolean check(SaveCanyinquanDto saveCanyinquanDto) {
        if (StringUtil.isEmpty(saveCanyinquanDto.getCanyinquanContent()) || saveCanyinquanDto.getCanyinquanPic1().isEmpty() ||
                ObjectUtil.isEmpty(saveCanyinquanDto.getLatitude()) || ObjectUtil.isEmpty(saveCanyinquanDto.getLongitude())) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCanyinquanById(CustCanyinquanEntityDto custCanyinquanEntityDto) {
        CustCanyinquanEntity custCanyinquanEntity = new CustCanyinquanEntity();
        BeanUtils.copyProperties(custCanyinquanEntityDto, custCanyinquanEntity);

        //获取城市id
        String cityName = TencentMapReverseGeocoding.getCity(custCanyinquanEntity.getLongitude().toString(), custCanyinquanEntity.getLatitude().toString());
        SysCityEntity cityEntity = sysCityDao.getCityByName(cityName);
        custCanyinquanEntity.setCityId(cityEntity.getCityId());
        custCanyinquanEntity.setCityName(cityName);
        //系统中发布餐饮圈是否需要审核
        SysConfCanyinquanShenheEntity canyinquanShenheEntity = sysConfCanyinquanShenheDao.getCanyinquanShenheEntity();
        custCanyinquanEntity.setCanyinquanState(canyinquanShenheEntity.getShenheState() == 1 ? 2 : 1);

        custCanyinquanEntity.setUpdateTime(new Date());
        custCanyinquanDao.updateByPrimaryKeySelective(custCanyinquanEntity);


        //修改的时候，先删除所有的图片，再重新录入
        custCanyinquanPicDao.delPicByCanyinquanId(custCanyinquanEntity.getCanyinquanId());

        //插入cust_canyinquan_pic
        List<CustCanyinquanPicEntity> canyinquanPicEntities = new ArrayList<>();
        List<String> picList = custCanyinquanEntityDto.getNonEmptyPictures();

        for (String canyinquanPic : picList) {
            CustCanyinquanPicEntity custCanyinquanPicEntity = new CustCanyinquanPicEntity();
            custCanyinquanPicEntity.setCanyinquanId(custCanyinquanEntity.getCanyinquanId());
            custCanyinquanPicEntity.setCanyinquanPicUrl(canyinquanPic);
            custCanyinquanPicEntity.setAddTime(new Date());
            canyinquanPicEntities.add(custCanyinquanPicEntity);
        }
        custCanyinquanPicDao.savaBatch(canyinquanPicEntities);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object insertDelDianzan(CustCanyinquanDianzanArticleEntity cdae, Integer type) {
        //1:点赞 2：取消点赞
        if (type == 1) {
            //是否重复点赞
            CustCanyinquanDianzanArticleEntity article = custCanyinquanDianzanArticleDao.selectOne(cdae);
            if (ObjectUtil.isNotEmpty(article)) {
                return "重复点赞";
            }
            cdae.setAddTime(new Date());
            custCanyinquanDianzanArticleDao.insertSelective(cdae);

            //文章表，修改数据
            CustCanyinquanEntity custCanyinquanEntity = custCanyinquanDao.selectByPrimaryKey(cdae.getCanyinquanId());
            CustCanyinquanEntity cc = new CustCanyinquanEntity();
            cc.setCanyinquanId(custCanyinquanEntity.getCanyinquanId());
            cc.setDianzanNum(custCanyinquanEntity.getDianzanNum() + 1);
            custCanyinquanDao.updateByPrimaryKeySelective(cc);

            return "ok";
        } else {
            int result = custCanyinquanDianzanArticleDao.delete(cdae);
            if (result > 0) {
                //文章表，修改数据
                CustCanyinquanEntity custCanyinquanEntity = custCanyinquanDao.selectByPrimaryKey(cdae.getCanyinquanId());
                CustCanyinquanEntity cc = new CustCanyinquanEntity();
                cc.setCanyinquanId(custCanyinquanEntity.getCanyinquanId());
                cc.setDianzanNum(custCanyinquanEntity.getDianzanNum() - 1);
                custCanyinquanDao.updateByPrimaryKeySelective(cc);
            }
            return "ok";
        }
    }

}